import {Component, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Globals} from '../../globals';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {NzNotificationService} from 'ng-zorro-antd/notification';
import {Router} from '@angular/router';
import {LayerService} from '../../shared/service/layer.service';
import {BaseService} from '../../shared/service/base.service';
import {Observable} from 'rxjs';
import {Consts} from '../../config/consts';
import {ApiUrl} from '../../config/api-url';
import {ForgetPasswordComponent} from './forget-password/forget-password.component';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  forgetPasswordVisible = false;
  @ViewChild('forgetPasswordComponent')
  forgetPasswordComponent: ForgetPasswordComponent;

  validateForm!: FormGroup;
  isMobile = Globals.isMobile();
  // 设备ID
  deviceId: any = Math.ceil(Math.random() * 1000000000000 + 1000000000000);

  currentYear = new Date().getFullYear();

  showImageCode = true;

  isLoading = false;

  // 获取验证码图片的url
  getCodeUrl = ApiUrl.CodeUrl;

  constructor(private fb: FormBuilder,
              private http: HttpClient,
              private router: Router,
              private base: BaseService,
              private layer: LayerService,
              private notification: NzNotificationService) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      imageCode: [null, [Validators.required]],
      remember: [true]
    });
    this.loadSessionUserNameAndPassword();
  }

  refreshImageCode() {
    this.showImageCode = false;
    setTimeout(() => {
      this.showImageCode = true;
    }, 1);
  }

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    const username = this.validateForm.value.username;
    const password = this.validateForm.value.password;
    const imageCode = this.validateForm.value.imageCode;
    this.login(username, password, imageCode);
  }


  login(username, password, imageCode) {
    this.isLoading = true;
    this.loginService(username, password, imageCode)
      .subscribe(
        data => {
          if (data.status == 0) {
            sessionStorage.setItem(Consts.ACCESS_TOKEN, data.access_token);
            if (!this.isMobile) {
              this.welcome();
            }
            this.setSessionUserNameAndPassword();
            this.getUserInfo();
            this.isLoading = false;
          }
        }, err => {
          if (err.status == 504) {
            this.layer.modalError('链接服务器超时,请检测服务器是否开启!');
          } else if (err.status == 404) {
            this.layer.modalError('后台登录服务已关闭,请联系管理员开启服务!');
          } else {
            this.layer.modalError(err.error.msg);
          }
          this.isLoading = false;
          if (err.error.msg == '图片验证码不存在' || err.error.msg == '用户名或密码错误') {
            this.refreshImageCode();
          }
        }
      );
  }

  getDate() {
    const now = new Date(), hour = now.getHours();
    if (hour < 6) {
      return '凌晨好！';
    } else if (hour < 9) {
      return '早上好！';
    } else if (hour < 12) {
      return '上午好！';
    } else if (hour < 14) {
      return '中午好！';
    } else if (hour < 17) {
      return '下午好！';
    } else if (hour < 19) {
      return '傍晚好！';
    } else if (hour < 22) {
      return '晚上好！';
    } else {
      return '夜里好！';
    }
  }

  welcome() {
    this.notification.create(
      'success',
      '欢迎',
      this.getDate() + '，欢迎回来!'
    );
  }

  /**
   * 用户登录获取用户token
   * @param username
   * @param password
   * @param imageCode
   */
  loginService(username, password, imageCode): Observable<any> {
    const headers = new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
      .append('Authorization', 'Basic aHVpTGlhbjpodWlMaWFuU2VjcmV0');

    const body = 'username=' + username + '&password=' + encodeURIComponent(password) + '&imageCode=' + imageCode + '&deviceId=' + this.deviceId;
    console.log('body: {}', body);
    const getTokenUrl = ApiUrl.AuthenticationUrl + '/form';
    return this.http.post(getTokenUrl, body, {headers});
  }

  /**
   * 获取用户信息
   */
  getUserInfo() {
    const url = ApiUrl.UserUrl + '/userInfo';
    this.base.get(url).subscribe(data => {
        if (data.status == 0) {
          console.log(data.data);
          // 保存用户信息到session
          sessionStorage.setItem(Consts.USER_INFO, JSON.stringify(data.data));

          // 跳转url
          const redirectUrl = sessionStorage.getItem(Consts.REDIRECT_URL);
          if (redirectUrl != null) {
            this.router.navigateByUrl(redirectUrl);
          } else {
            this.router.navigateByUrl('');
          }
        } else {
          this.layer.modalError(data.msg);
        }
      }, err => {
        if (err.status == 504) {
          this.layer.modalError('链接服务器超时,请检测服务器是否开启!');
        } else if (err.status == 404) {
          this.layer.modalError('后台登录服务已关闭,请联系管理员开启服务!');
        } else {
          this.layer.modalError(err.error.msg);
          console.log(err);
        }
      }
    );
  }

  // 加载浏览器缓存中的账号和密码
  loadSessionUserNameAndPassword() {
    const username = localStorage.getItem(Consts.USERNAME);
    const password = localStorage.getItem(Consts.PASSWORD);
    const remember = localStorage.getItem(Consts.REMEMBER);
    if (password != undefined) {
      this.validateForm.reset({
          username,
          password,
          remember
        }
      );
    }
  }

  setSessionUserNameAndPassword() {
    const remember = this.validateForm.value.remember;
    if (remember) {
      localStorage.setItem(Consts.USERNAME, this.validateForm.value.username);
      localStorage.setItem(Consts.PASSWORD, this.validateForm.value.password);
      localStorage.setItem(Consts.REMEMBER, String(remember));
    } else {
      localStorage.removeItem(String(remember));
      localStorage.removeItem(Consts.USERNAME);
      localStorage.removeItem(Consts.PASSWORD);
    }
  }

  settingForgetPassword($event: any) {
    this.forgetPasswordVisible = $event;
  }

  showForgetPassword() {
    this.forgetPasswordVisible = true;
    // this.cardAddComponent.loadingModal();
  }
}
